<template>
  <div class="container">
    <div class="page-header">
      <h3>创建主题表</h3>
      <p>请选择数据源并配置相关参数</p>
    </div>
    <el-card class="source-card" shadow="hover">
      <div class="source-container">
        <label class="source-label">数据源：</label>
        <el-select
          v-model="dataSourceId"
          placeholder="请选择连接池"
          style="width: 250px"
          @change="handleDataSourceSelectionChange"
        >
          <el-option
            v-for="item in fieldoptions"
            :key="item.id"
            :label="item.aliasName || item.dataSourceName"
            :value="item.id!"
          />
        </el-select>
      </div>
    </el-card>
    <el-card class="transfer-card" shadow="hover">
      <div class="transfer-header">
        <h4>指标选择</h4>
        <p>请从左侧选择需要的指标，添加到右侧</p>
      </div>
      <el-transfer
        v-model="targetKeys"
        :data="transferData"
        :render-content="renderContent"
        :titles="['源列表', '目标列表']"
        filterable
        :filter-method="filterMethod"
        @change="handlerTransferChange"
        @right-check-change="handlerRightCheckChange"
      />
    </el-card>
    <el-card class="config-card" shadow="hover">
      <div class="config-header">
        <h4>指标配置</h4>
      </div>
      <div class="config-container">
        <el-card class="sub-card" shadow="hover">
          <div class="sub-card-header">
            <h4>公有维度</h4>
          </div>
          <el-table :data="publicDimensionList" border @selection-change="handlerTableChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="dimensionColumn" label="公有维度" width="150" />
          </el-table>
        </el-card>
        <!-- 数据期列 -->
        <el-card class="sub-card" shadow="hover">
          <div class="sub-card-header">
            <h4>数据期列</h4>
          </div>
          <el-radio-group v-model="selectedOption">
            <el-radio label="dropdown">选择数据期列</el-radio>
            <!-- <el-radio label="custom">自定义数据期列</el-radio> -->
          </el-radio-group>
          <div v-if="selectedOption === 'dropdown'">
            <el-select
              v-model="form.timePeriodId"
              class="m-2"
              placeholder="请选择字段类型"
              size="large"
              style="width: 200px"
              @change="handlerSelectChange"
            >
              <el-option
                v-for="item in timePeriodOptins"
                :key="item.id"
                :label="item.timeColumn"
                :value="item.id!"
              />
            </el-select>
          </div>
          <!-- <div v-if="selectedOption === 'custom'">
          <el-input v-model="customTimePeriod" placeholder="请输入自定义数据期列" />
        </div> -->
        </el-card>

        <!-- 新增的显示私有维度模块 -->
        <el-card class="sub-card" shadow="hover">
          <div class="sub-card-header">
            <h4>私有维度</h4>
          </div>
          <div
            v-for="(indicatorId, index) in checkedIndicatorIds"
            :key="index"
            class="private-dimension-item"
          >
            <h5>指标名称: {{ getIndicatorName(indicatorId) }}</h5>
            <el-table
              ref="(el) => privateDimensionTables[indicatorId] = el"
              :data="getPrivateDimensions(indicatorId)"
              border
              @selection-change="(selection) => handlerPrivateTableChange(selection, indicatorId)"
            >
              <!-- 移除私有维度表格中的勾选框 -->
              <el-table-column prop="dimensionColumn" label="私有维度" width="150" />
              <el-table-column prop="dimensionValue" label="纬度值" width="180">
                <template #default="{ row }">
                  <el-select
                    v-model="row.dimensionValue"
                    placeholder="请选择维度值"
                    :loading="dimensionValueLoading[row.id]"
                    @change="(value) => handleDimensionValueChange(row.id, value)"
                  >
                    <el-option
                      v-for="item in dimensionValueOptions[row.id] || []"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>
    </el-card>
    <div class="button-container">
      <el-button type="primary" size="large" @click="nextStep">下一步</el-button>
      <el-button size="large" @click="closedDialog">关闭</el-button>
    </div>
    <el-dialog v-model="isConfigVisble">
      <el-table :data="indicatorInfoList" border>
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="tableName" label="表名称" width="100" />
        <el-table-column prop="columnName" label="字段" width="100" />
        <el-table-column prop="alias" label="别名" width="100">
          <template #default="{ row }">
            <el-input v-model="row.alias" />
          </template>
        </el-table-column>
        <el-table-column prop="indicatorName" label="标题" width="100" />
        <el-table-column prop="typeName" label="字段类型" width="100" />
        <el-table-column prop="pk" label="是否是主键" width="100" />
        <el-table-column prop="dataType" label="数据类型" width="100" />
        <el-table-column prop="size" label="数据长度" width="100" />
        <el-table-column prop="digit" label="数据精度" width="100" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isConfigVisble = false">上一步</el-button>
          <el-button type="primary" @click="openCreateDialog">下一步</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="isCreateVisble">
      <el-form :model="form" label-width="auto">
        <el-form-item label="主题表名称">
          <el-input v-model="form.tableName" />
        </el-form-item>
        <el-form-item label="创建人">
          <el-input v-model="form.createUser" />
        </el-form-item>
        <el-form-item label="创建时间">
          <!-- <el-input v-model="form.crateTime" /> -->
          <el-date-picker v-model="form.crateTime" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item label="是否审核">
          <el-switch v-model="review" inline-prompt active-text="是" inactive-text="否" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="sumbit">完成</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<!-- </template> -->
<script lang="ts">
export default { name: "CreateThemeTable" };
</script>
<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import IndicatorThemeAPI, {
  ThemeInsertParameter,
  IndicatorDimensionList,
  IndicatorIds,
  IndicatorDimensionListResponse,
  IndciatorDimension,
  IndciatorTimePeriodListResponse,
  IndicatorInfoListResponse,
  CreateTableParameter,
  ColumnsConfig,
  DimensionValueList,
} from "@/api/themeTable/index";
import indicatorDomainAPI, {
  DomainListParameter,
  DomainListResponse,
  IndicatorList,
  IndicatorPrivateDimensionValue,
} from "@/api/indicationManage/domain";
import IndicatorManageAPI, { DataSourceList } from "@/api/strategy/strategy-index-database";
const props = defineProps<{
  dataSourceId: any;
  dataSourceName: any;
  domainId: any;
}>();
const emit = defineEmits(["success", "close"]);
const domainListResponse = ref<DomainListResponse>();
const domainList = ref<IndicatorList[]>([]);
const transferData = ref<any[]>([]);
const targetKeys = ref<number[]>([]);
const indicatorIds = reactive<IndicatorIds>({});
const indicatorDimensionListResponse = ref<IndicatorDimensionListResponse>();
const privateDimensionList = ref<IndciatorDimension[]>();
const publicDimensionList = ref<IndciatorDimension[]>();
const isCreateVisble = ref(false);
const isConfigVisble = ref(false);
const fieldoptions = ref<DataSourceList[]>();

const indicatorInfoList = ref<IndicatorInfoListResponse[]>();
//存储勾选的数据
const selectRows = ref<IndciatorDimension[]>();
const form = reactive<ThemeInsertParameter>({
  indicatorDimensions: [] as IndicatorDimensionList[],
  dimensionValues: [] as IndicatorPrivateDimensionValue[], // 存储维度ID和值的映射集合
  domainId: props.domainId,
});

const domainListParameter = reactive<DomainListParameter>({});
const themeTableId = ref<number>();
const createTableParameter = reactive<CreateTableParameter>({});

const review = ref(false);

const dataSourceId = ref(props.dataSourceId);

async function handlerQuery() {
  fieldoptions.value = await IndicatorManageAPI.DataSourceList();
  if (props.dataSourceId !== 0 && props.dataSourceId !== null) {
    domainListParameter.dataSourceId = props.dataSourceId;
    const response = await indicatorDomainAPI.SelectDomainTree(domainListParameter);
    domainListResponse.value = response;
    domainList.value = domainListResponse.value.indicatorList!;
    transferData.value = processData(domainList.value);
  }
}

const handleDataSourceSelectionChange = async () => {
  domainListParameter.dataSourceId = dataSourceId.value;
  const response = await indicatorDomainAPI.SelectDomainTree(domainListParameter);
  domainListResponse.value = response;
  domainList.value = domainListResponse.value.indicatorList!;
  transferData.value = processData(domainList.value);
};

const timePeriodOptins = ref<IndciatorTimePeriodListResponse[]>();

// 处理数据，只保留 indicatorGroups 及以下数据
const processData = (data: any[]) => {
  return data.flatMap((item: any) => {
    console.log(item);
    return item.indicatorGroups
      .map((group: any) => {
        return group.indicators.map((indicator: any) => {
          return {
            key: indicator.id,
            label: indicator.indicatorName,
            groupName: group.domainName,
          };
        });
      })
      .flat();
  });
};

// 自定义渲染内容
const renderContent = (h: any, option: any) => {
  return h("span", option.label);
};

// 过滤方法
const filterMethod = (query: string, option: any) => {
  return option.label.includes(query) || option.groupName.includes(query);
};
// 新增状态
const selectedOption = ref("dropdown");
const customTimePeriod = ref("");

const handlerTransferChange = async () => {
  if (targetKeys.value.length > 0) {
    indicatorIds.indicatorIds = targetKeys.value;
    const response = await IndicatorThemeAPI.DimensionList(indicatorIds);
    indicatorDimensionListResponse.value = response;
    publicDimensionList.value = indicatorDimensionListResponse.value.publicDimensionList;
    privateDimensionList.value = indicatorDimensionListResponse.value.privateDimensionList;
    const timeColumnListResponse = await IndicatorThemeAPI.TimePeriodList(indicatorIds);
    timePeriodOptins.value = timeColumnListResponse;
    form.indicatorIds = targetKeys.value;
  } else {
    checkedIndicatorIds.value = [];
    form.indicatorIds = [];
  }
};

const handlerTableChange = (item: IndciatorDimension[]) => {
  selectRows.value = item;
  // 清空之前的 dimensionIds
  form.dimensionIds = [] as number[];
  // 遍历选中的行，将 id 赋值给 dimensionIds
  item.forEach((row: any) => {
    form.dimensionIds!.push(row.id);
  });
};

// 新增：存储勾选的 indicatorId 列表
const checkedIndicatorIds = ref<number[]>([]);

// 存储维度值下拉选项
const dimensionValueOptions = reactive<Record<number, { value: string; label: string }[]>>({});

// 存储维度值加载状态
const dimensionValueLoading = reactive<Record<number, boolean>>({});

// 根据维度ID查询维度值选项
const fetchDimensionValues = async (dimensionId: number) => {
  if (dimensionValueLoading[dimensionId]) return;

  dimensionValueLoading[dimensionId] = true;
  try {
    const response = await IndicatorThemeAPI.ValueById({
      id: dimensionId,
    });
    // 由于ValueById返回的是单个对象，我们需要将其包装成数组
    dimensionValueOptions[dimensionId] = response.map((item: DimensionValueList) => ({
      value: item.value || "",
      label: item.label || "",
    }));
  } catch (error) {
    console.error(`查询维度值失败: ${dimensionId}`, error);
    ElMessage.error(`查询维度值失败: ${error instanceof Error ? error.message : String(error)}`);
  } finally {
    dimensionValueLoading[dimensionId] = false;
  }
};

// 只在privateDimensionList变化时加载维度值
watch(
  privateDimensionList,
  (newList) => {
    if (newList) {
      newList.forEach((dimension) => {
        if (
          dimension.id &&
          !dimensionValueOptions[dimension.id] &&
          !dimensionValueLoading[dimension.id]
        ) {
          fetchDimensionValues(dimension.id);
        }
      });
    }
  },
  { immediate: true }
);

const handlerRightCheckChange = (checkedKeys: any[]) => {
  checkedIndicatorIds.value = checkedKeys;
};

// 获取指定指标的私有维度
const getPrivateDimensions = (indicatorId: number) => {
  return privateDimensionList.value?.filter((d) => d.indicatorId === indicatorId) || [];
};

// 获取指标名称
const getIndicatorName = (indicatorId: number) => {
  const item = transferData.value.find((i) => i.key === indicatorId);
  return item ? item.label : "未知指标";
};

const handlerSelectChange = () => {
  console.log("数据期列已选择:", form.timePeriodId);
  // 选择数据期列后，恢复私有维度的勾选状态
  setTimeout(() => {
    restorePrivateDimensionSelection();
  }, 0);
};

// 存储私有维度表格的ref
const privateDimensionTables = ref<Record<number, any>>({});

// 处理维度值变化
const handleDimensionValueChange = (dimensionId: number, value: string) => {
  // 查找维度对应的指标 ID
  const dimension = privateDimensionList.value?.find((d) => d.id === dimensionId);
  if (!dimension) return;

  const indicatorId = dimension.indicatorId;

  // 查找或创建对应的 IndicatorDimensionList 对象
  let indicatorDimension = form.indicatorDimensions?.find(
    (item) => item.indicatorId === indicatorId
  );

  if (!indicatorDimension) {
    // 创建新的 IndicatorDimensionList 对象
    indicatorDimension = {
      indicatorId: indicatorId,
      dimensionIds: [],
      dimensionValues: [],
    };
    form.indicatorDimensions?.push(indicatorDimension);
  }

  // 确保 dimensionIds 中包含当前维度 ID
  if (!indicatorDimension.dimensionIds?.includes(dimensionId)) {
    indicatorDimension.dimensionIds?.push(dimensionId);
  }

  // 更新维度值
  const valueIndex = indicatorDimension.dimensionValues?.findIndex(
    (v) => v.dimensionId === dimensionId
  );

  if (valueIndex !== -1 && valueIndex !== undefined) {
    indicatorDimension.dimensionValues![valueIndex].value = value;
  } else {
    indicatorDimension.dimensionValues?.push({
      dimensionId: dimensionId,
      value: value,
    });
  }

  // 查找是否已存在该维度的记录
  const existingIndex = form.dimensionValues.findIndex((item) => item.dimensionId === dimensionId);

  if (existingIndex !== -1) {
    // 更新已有记录
    form.dimensionValues[existingIndex].value = value;
  } else {
    // 添加新记录
    form.dimensionValues.push({
      dimensionId: dimensionId,
      value: value,
    });
  }

  console.log("维度值已更新:", form.dimensionValues);
};

const handlerPrivateTableChange = (item: IndciatorDimension[], indicatorId: number) => {
  // 先清空 form.indicatorDimensions 中所有与当前操作指标相关的数据
  if (indicatorId) {
    form.indicatorDimensions = form.indicatorDimensions!.filter(
      (dim) => dim.indicatorId !== indicatorId
    );
  }

  if (item.length === 0) return; // 如果没有选中项，直接返回

  const indicatorDimensionList = reactive<IndicatorDimensionList>({
    indicatorId: indicatorId,
    dimensionIds: [],
    dimensionValues: [] as { dimensionId: number; value: string }[],
  });

  item.forEach((row: any) => {
    indicatorDimensionList.dimensionIds!.push(row.id);
    // 收集维度值
    if (row.dimensionValue) {
      indicatorDimensionList.dimensionValues.push({
        dimensionId: row.id,
        value: row.dimensionValue,
      });

      // 同时更新 form.dimensionValues
      const existingIndex = form.dimensionValues.findIndex((item) => item.dimensionId === row.id);
      if (existingIndex !== -1) {
        form.dimensionValues[existingIndex].value = row.dimensionValue;
      } else {
        form.dimensionValues.push({
          dimensionId: row.id,
          value: row.dimensionValue,
        });
      }
    }
  });

  // 添加新的 IndicatorDimensionList 数据
  form.indicatorDimensions!.push(indicatorDimensionList);
};

// 恢复私有维度表格的勾选状态
const restorePrivateDimensionSelection = () => {
  if (!form.indicatorDimensions || form.indicatorDimensions.length === 0) return;

  form.indicatorDimensions.forEach((dim) => {
    const tableRef = privateDimensionTables.value[dim.indicatorId];
    if (tableRef) {
      const privateDimensions = getPrivateDimensions(dim.indicatorId);
      const rowsToSelect = privateDimensions.filter((row) => dim.dimensionIds?.includes(row.id));
      tableRef.toggleRowSelection(rowsToSelect, true);
    }
  });
};

const nextStep = async () => {
  isConfigVisble.value = true;
  const response = await IndicatorThemeAPI.IndicatorInfoList(indicatorIds);
  indicatorInfoList.value = response;
};

const openCreateDialog = () => {
  isCreateVisble.value = true;
  form.createUser = getCurrentUsername();
};

// 从localStorage获取用户信息
const getUserInfo = () => {
  const userInfoStr = localStorage.getItem("userInfo");
  if (userInfoStr) {
    try {
      return JSON.parse(userInfoStr);
    } catch (error) {
      console.error("解析用户信息失败:", error);
      return null;
    }
  }
  return null;
};

// 获取当前用户名
const getCurrentUsername = () => {
  const userInfo = getUserInfo();
  return userInfo?.username || "";
};

const sumbit = async () => {
  isConfigVisble.value = false;
  isCreateVisble.value = false;
  console.log(form);
  const response = await IndicatorThemeAPI.Insert(form);
  themeTableId.value = response.themeTableId;
  createTableParameter.themeTableId = themeTableId.value;

  // 处理维度值
  const dimensionValues =
    form.indicatorDimensions?.flatMap((dim) => {
      return (
        dim.dimensionValues?.map((val) => ({
          indicatorId: dim.indicatorId,
          dimensionId: val.dimensionId,
          value: val.value,
        })) || []
      );
    }) || [];
  createTableParameter.dimensionValues = dimensionValues;

  const columnsConfigList = indicatorInfoList.value?.map((item: any) => {
    return {
      tableName: item.tableName,
      indicatorId: item.id,
      indicatorName: item.indicatorName,
      columnName: item.columnName,
      alias: item.alias,
      description: item.description,
      dataType: item.dataType,
      size: item.size,
      digit: item.digit,
    } as unknown as ColumnsConfig;
  });
  createTableParameter.columns = columnsConfigList;
  console.log(createTableParameter);
  await IndicatorThemeAPI.CreateTable(createTableParameter).then(() => {
    sessionStorage.setItem("themeTableId", JSON.stringify(themeTableId.value));
    emit("success", {
      themeTableId: themeTableId.value,
      dataSourceId: dataSourceId.value,
    });
    ElMessage.success("添加完成");
  });
};

const closedDialog = () => {
  emit("close", {
    dataSourceId: dataSourceId.value,
  });
  console.log("触发关闭事件");
};

onMounted(() => {
  handlerQuery();
  form.tableMysqlName = props.dataSourceName;
});
</script>
<style lang="scss">
.container {
  // background-color: #f5f7fa;
  min-height: 100%;
  padding: 20px;
}

.page-header {
  padding-bottom: 10px;
  margin-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.page-header h3 {
  margin: 0;
  font-size: 18px;
  color: #ffffff;
}

.page-header p {
  margin: 5px 0 0;
  font-size: 14px;
  color: #f0f1f3;
}

.source-card {
  margin-bottom: 20px;
}

.source-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.source-label {
  min-width: 60px;
  font-size: 14px;
  color: #606266;
}

.transfer-card,
.config-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.transfer-header,
.config-header {
  padding-bottom: 10px;
  margin-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.transfer-header h4,
.config-header h4 {
  margin: 0;
  font-size: 16px;
  color: #f7f8fa;
}

.transfer-header p {
  margin: 5px 0 0;
  font-size: 14px;
  color: #f0f1f3;
}

.config-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
}

.sub-card {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.sub-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
}

.sub-card-header {
  padding-bottom: 8px;
  margin-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.sub-card-header h4 {
  margin: 0;
  font-size: 15px;
  color: #f7f8fa;
}

.button-container {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  padding-top: 20px;
  margin-top: 30px;
  // border-top: 1px solid #e4e7ed;
}

.private-dimension-item {
  padding-top: 10px;
  margin-top: 10px;
  border-top: 1px dashed #e4e7ed;
}

.private-dimension-item:first-child {
  padding-top: 0;
  margin-top: 0;
  border-top: none;
}

.private-dimension-item h5 {
  margin-bottom: 12px;
  font-size: 14px;
  color: #409eff;
}

.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.el-dialog .dialog-footer {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  margin-top: 30px;
}

.el-transfer-panel {
  border-radius: 4px;
}

.el-table th {
  background-color: #f7f8fa;
}

.el-table {
  margin-bottom: 15px;
}

.el-button + .el-button {
  margin-left: 10px;
}

.el-dialog .el-form {
  margin-top: 20px;
}

.el-dialog .el-form-item {
  margin-bottom: 25px;
}

.el-radio-group {
  margin-bottom: 15px;
}

* {
  box-sizing: border-box;
}

.transfer-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;
}

.dimension-container,
.data-period-container,
.private-dimension-container {
  padding: 15px;
}

h4 {
  padding-bottom: 5px;
  margin-bottom: 10px;
  font-size: 16px;
  border-bottom: 1px solid #e4e7ed;
}

h5 {
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}
</style>
